package models

import "fmt"

type Address struct {
    ID          int     `json:"id"`             // 地址ID
    UserID      int     `json:"user_id"`        // 用户ID
    Addressee   string  `json:"addressee"`      // 收件人信息
    Phonenumber string  `json:"phonenumber"`    // 收件人电话
    Address     string  `json:"address"`        // 收件人地址
    IsDefault   bool    `json:"is_default"`     // 是否为默认地址
}

// AddAddress 添加新地址
func AddAddress(address Address) (int64, error) {
    // 如果设置为默认地址，先将该用户的其他地址设为非默认
    if address.IsDefault {
        _, err := db.Exec("UPDATE addresses SET is_default = 0 WHERE user_id = ?", address.UserID)
        if err != nil {
            return 0, fmt.Errorf("更新默认地址状态失败: %v", err)
        }
    }

    result, err := db.Exec(`
        INSERT INTO addresses (user_id, addressee, phonenumber, address, is_default)
        VALUES (?, ?, ?, ?, ?)`,
        address.UserID, address.Addressee, address.Phonenumber, address.Address, address.IsDefault)
    if err != nil {
        return 0, fmt.Errorf("添加地址失败: %v", err)
    }

    return result.LastInsertId()
}

// GetUserAddresses 获取用户的所有地址
func GetUserAddresses(userID int) ([]Address, error) {
    rows, err := db.Query(`
        SELECT id, user_id, addressee, phonenumber, address, is_default
        FROM addresses
        WHERE user_id = ?
        ORDER BY is_default DESC`, userID)
    if err != nil {
        return nil, fmt.Errorf("获取地址列表失败: %v", err)
    }
    defer rows.Close()

    var addresses []Address
    for rows.Next() {
        var address Address
        err := rows.Scan(
            &address.ID, &address.UserID, &address.Addressee, &address.Phonenumber, &address.Address, &address.IsDefault)
        if err != nil {
            return nil, fmt.Errorf("扫描地址数据失败: %v", err)
        }
        addresses = append(addresses, address)
    }

    return addresses, nil
}

// GetUserAddressByID 根据address_id获取用户的具体地址
func GetUserAddressByID(userID int, address_id int) (Address, error) {
    var address Address
    err := db.QueryRow(`
        SELECT id, user_id, addressee, phonenumber, address, is_default
        FROM addresses
        WHERE user_id = ? AND id =?
        ORDER BY is_default DESC`, userID, address_id).Scan(
            &address.ID, &address.UserID, &address.Addressee, &address.Phonenumber, &address.Address, &address.IsDefault)
    if err != nil {
        return Address{}, fmt.Errorf("获取地址列表失败: %v", err)
    }

    return address, nil
}

// UpdateAddress 更新地址信息
func UpdateAddress(address Address) error {
    if address.IsDefault {
        _, err := db.Exec("UPDATE addresses SET is_default = 0 WHERE user_id = ?", address.UserID)
        if err != nil {
            return fmt.Errorf("更新默认地址状态失败: %v", err)
        }
    }

    result, err := db.Exec(`
        UPDATE addresses 
        SET addressee = ?, phonenumber = ?, address = ? , is_default =?
        WHERE id = ? AND user_id = ?`,
        address.Addressee, address.Phonenumber, address.Address, address.IsDefault,
        address.ID, address.UserID)
    if err != nil {
        return fmt.Errorf("更新地址失败: %v", err)
    }

    rows, err := result.RowsAffected()
    if err != nil {
        return fmt.Errorf("获取影响行数失败: %v", err)
    }
    if rows == 0 {
        return fmt.Errorf("地址不存在或无权更新")
    }

    return nil
}

// DeleteAddress 删除地址
func DeleteAddress(addressID, userID int) error {
    result, err := db.Exec("DELETE FROM addresses WHERE id = ? AND user_id = ?", addressID, userID)
    if err != nil {
        return fmt.Errorf("删除地址失败: %v", err)
    }

    rows, err := result.RowsAffected()
    if err != nil {
        return fmt.Errorf("获取影响行数失败: %v", err)
    }
    if rows == 0 {
        return fmt.Errorf("地址不存在或无权删除")
    }

    return nil
}

// GetDefaultAddress 获取用户的默认地址
func GetDefaultAddress(userID int) (Address, error) {
    var address Address
    err := db.QueryRow(`
        SELECT id, user_id, address, addressee, phonenumber, is_default
        FROM addresses
        WHERE user_id = ? AND is_default = 1`, userID).Scan(
        &address.ID, &address.UserID, &address.Addressee, &address.Phonenumber, &address.Address, &address.IsDefault)
    if err != nil {
        return Address{}, fmt.Errorf("获取默认地址失败: %v", err)
    }

    return address, nil
} 